import { ref, reactive } from "vue";
import { logout, updatepassword } from "@/api/manager";
import { showModal, toast } from "@/composables/util";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

//修改密码
export function useRepassword() {
  const router = useRouter();
  const store = useStore();
  //修改密码部分--子组件暴露了方法--父组件通过formDrawerRef摸到方法
  const formDrawerRef = ref(null);

  const form = reactive({
    oldpassword: "",
    password: "",
    repassword: "",
  });

  const formRef = ref(null);

  const rules = {
    oldpassword: [
      {
        required: true,
        message: "旧密码不能为空",
        trigger: "blur",
      },
    ],
    password: [
      {
        required: true,
        message: "新密码不能为空",
        trigger: "blur",
      },
    ],
    repassword: [
      {
        required: true,
        message: "确认密码不能为空",
        trigger: "blur",
      },
    ],
  };

  const onSubmit = () => {
    formRef.value.validate((valid) => {
      if (!valid) {
        return false;
      }
      // loading.value = true
      formDrawerRef.value.showloading();
      updatepassword(form)
        .then((res) => {
          toast("修改密码成功,请重新登录");
          store.dispatch("logout");
          router.push("/login");
        })
        .finally(() => {
          // loading.value = false
          formDrawerRef.value.hideloading();
        });
    });
  };

  const openRepasswordForm = () => formDrawerRef.value.open();

  return {
    formDrawerRef,
    form,
    formRef,
    rules,
    onSubmit,
    openRepasswordForm,
  };
}

//退出登录
export function uselogout() {
  const router = useRouter();
  const store = useStore();
  function handlelogout() {
    showModal("是否要退出登录？").then((res) => {
      logout().finally(() => {
        //触发logout的action--action执行操作
        store.dispatch("logout");
        //跳转回登录页
        router.push("/login");
        //提示退出登录成功
        toast("退出登录成功");
      });
    });
  }

  return {
    handlelogout,
  };
}
